'use client'

import { useState, useEffect } from 'react'
import { StarDisplay } from '@/components/ui/star-rating'
import { BarChart3, Users, MessageCircle } from 'lucide-react'

interface ReviewStatsProps {
  toolId: string
}

interface ReviewStats {
  totalReviews: number
  averageRating: number
  ratingDistribution: {
    1: number
    2: number
    3: number
    4: number
    5: number
  }
}

export function ReviewStats({ toolId }: ReviewStatsProps) {
  const [stats, setStats] = useState<ReviewStats | null>(null)
  const [loading, setLoading] = useState(true)

  useEffect(() => {
    fetchStats()
  }, [toolId])

  const fetchStats = async () => {
    try {
      setLoading(true)
      const response = await fetch(`/api/tools/${toolId}/reviews/stats`)
      const result = await response.json()

      if (response.ok) {
        setStats(result.data)
      }
    } catch (error) {
      console.error('获取评价统计失败:', error)
    } finally {
      setLoading(false)
    }
  }

  if (loading) {
    return (
      <div className="bg-gray-50 rounded-lg p-4">
        <div className="animate-pulse space-y-3">
          <div className="h-4 bg-gray-200 rounded w-1/3"></div>
          <div className="h-3 bg-gray-200 rounded w-1/2"></div>
          <div className="space-y-2">
            {[1, 2, 3, 4, 5].map(i => (
              <div key={i} className="flex items-center space-x-2">
                <div className="h-3 bg-gray-200 rounded w-8"></div>
                <div className="h-2 bg-gray-200 rounded flex-1"></div>
                <div className="h-3 bg-gray-200 rounded w-8"></div>
              </div>
            ))}
          </div>
        </div>
      </div>
    )
  }

  if (!stats || stats.totalReviews === 0) {
    return (
      <div className="bg-gray-50 rounded-lg p-6 text-center">
        <MessageCircle className="h-12 w-12 text-gray-400 mx-auto mb-3" />
        <h3 className="text-lg font-medium text-gray-900 mb-2">暂无评价</h3>
        <p className="text-gray-500">成为第一个评价这个工具的用户吧！</p>
      </div>
    )
  }

  const maxCount = Math.max(...Object.values(stats.ratingDistribution))

  return (
    <div className="bg-gray-50 rounded-lg p-6">
      <div className="flex items-center justify-between mb-4">
        <h3 className="text-lg font-semibold text-gray-900">用户评价</h3>
        <div className="flex items-center space-x-1 text-sm text-gray-500">
          <Users className="h-4 w-4" />
          <span>{stats.totalReviews} 条评价</span>
        </div>
      </div>

      {/* 总体评分 */}
      <div className="flex items-center space-x-4 mb-6">
        <div className="text-center">
          <div className="text-3xl font-bold text-gray-900">
            {stats.averageRating.toFixed(1)}
          </div>
          <StarDisplay rating={stats.averageRating} size="sm" />
        </div>
        
        <div className="flex-1">
          <div className="text-sm text-gray-600 mb-2">评分分布</div>
          <div className="space-y-1">
            {[5, 4, 3, 2, 1].map(rating => {
              const count = stats.ratingDistribution[rating as keyof typeof stats.ratingDistribution]
              const percentage = stats.totalReviews > 0 ? (count / stats.totalReviews) * 100 : 0
              const width = maxCount > 0 ? (count / maxCount) * 100 : 0

              return (
                <div key={rating} className="flex items-center space-x-2 text-xs">
                  <span className="w-3 text-gray-600">{rating}</span>
                  <div className="flex-1 bg-gray-200 rounded-full h-2">
                    <div 
                      className="bg-yellow-400 h-2 rounded-full transition-all duration-300"
                      style={{ width: `${width}%` }}
                    />
                  </div>
                  <span className="w-8 text-gray-600 text-right">{count}</span>
                  <span className="w-10 text-gray-500 text-right">
                    {percentage.toFixed(0)}%
                  </span>
                </div>
              )
            })}
          </div>
        </div>
      </div>

      {/* 快速统计 */}
      <div className="grid grid-cols-3 gap-4 pt-4 border-t border-gray-200">
        <div className="text-center">
          <div className="text-lg font-semibold text-gray-900">
            {stats.totalReviews}
          </div>
          <div className="text-xs text-gray-500">总评价数</div>
        </div>
        
        <div className="text-center">
          <div className="text-lg font-semibold text-gray-900">
            {stats.averageRating.toFixed(1)}
          </div>
          <div className="text-xs text-gray-500">平均评分</div>
        </div>
        
        <div className="text-center">
          <div className="text-lg font-semibold text-gray-900">
            {((stats.ratingDistribution[4] + stats.ratingDistribution[5]) / stats.totalReviews * 100).toFixed(0)}%
          </div>
          <div className="text-xs text-gray-500">好评率</div>
        </div>
      </div>
    </div>
  )
}
